<script setup>
import { ref, computed, shallowRef, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { useTemplateStore } from '@/stores/template';
import { useDocumentStore } from '@/stores/document';
// 导入wangEditor
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
// 导入Element Plus的Message组件
import { ElMessage, ElMessageBox } from 'element-plus';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const templateStore = useTemplateStore();
const documentStore = useDocumentStore();

// 获取模板ID
const templateId = computed(() => route.params.id);

// 模板数据
const template = ref(null);
const loading = ref({
  template: false,
  save: false,
  delete: false,
  createDocument: false
});
const error = ref(null);

// 编辑模式
const isEditMode = ref(false);
const editForm = ref({
  name: '',
  content: '',
  category: ''
});

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 编辑器内容
const editorValue = ref('');

// 编辑器配置
const editorConfig = {
  placeholder: '请输入模板内容...',
  MENU_CONF: {}
};

// 获取模板详情
const fetchTemplate = async () => {
  if (!templateId.value) return;
  
  loading.value.template = true;
  error.value = null;
  
  try {
    template.value = await templateStore.fetchTemplateById(templateId.value);
    
    if (!template.value) {
      error.value = '模板不存在';
      return;
    }
    
    // 初始化编辑表单
    editForm.value = {
      name: template.value.name,
      content: template.value.content,
      category: template.value.category || ''
    };
    
    // 初始化编辑器内容
    editorValue.value = template.value.content;
  } catch (err) {
    console.error('Failed to fetch template:', err);
    error.value = '获取模板详情失败';
  } finally {
    loading.value.template = false;
  }
};

// 检查是否有编辑权限
const canEdit = computed(() => {
  return userStore.isAdmin;
});

// 切换编辑模式
const toggleEditMode = () => {
  if (!canEdit.value) return;
  
  isEditMode.value = !isEditMode.value;
  
  if (isEditMode.value) {
    // 进入编辑模式，初始化表单
    editForm.value = {
      name: template.value.name,
      content: template.value.content,
      category: template.value.category || ''
    };
    
    // 初始化编辑器内容
    editorValue.value = template.value.content;
  }
};

// 保存模板
const saveTemplate = async () => {
  if (!templateId.value || !isEditMode.value) return;
  
  loading.value.save = true;
  error.value = null;
  
  try {
    // 使用编辑器内容更新模板
    const updated = await templateStore.updateTemplate(templateId.value, {
      name: editForm.value.name,
      content: editorValue.value,
      category: editForm.value.category || null
    });
    
    if (updated) {
      // 更新成功，退出编辑模式并刷新模板数据
      isEditMode.value = false;
      await fetchTemplate();
      // 显示成功消息
      ElMessage({
        message: '模板保存成功',
        type: 'success'
      });
    }
  } catch (err) {
    console.error('Failed to save template:', err);
    error.value = '保存模板失败';
    // 显示错误消息
    ElMessage({
      message: '保存模板失败',
      type: 'error'
    });
  } finally {
    loading.value.save = false;
  }
};

// 从模板创建文档
const createDocumentFromTemplate = async () => {
  if (!templateId.value) return;
  
  loading.value.createDocument = true;
  error.value = null;
  
  try {
    const documentId = await documentStore.createDocument(
      `基于模板: ${template.value.name}`,
      template.value.content,
      templateId.value
    );
    
    if (documentId) {
      // 创建成功，跳转到文档编辑页面
      router.push(`/documents/${documentId}`);
      // 显示成功消息
      ElMessage({
        message: '文档创建成功',
        type: 'success'
      });
    }
  } catch (err) {
    console.error('Failed to create document from template:', err);
    error.value = '创建文档失败';
    // 显示错误消息
    ElMessage({
      message: '创建文档失败',
      type: 'error'
    });
  } finally {
    loading.value.createDocument = false;
  }
};

// 删除模板
const deleteTemplate = async () => {
  if (!templateId.value) return;
  
  // 使用Element Plus的MessageBox进行确认操作
  ElMessageBox.confirm(
    '确定要删除此模板吗？此操作不可撤销。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      // 用户点击确认，执行删除操作
      await performDelete();
    })
    .catch(() => {
      // 用户取消操作
      ElMessage({
        type: 'info',
        message: '已取消删除'
      });
    });
};

// 执行删除操作
const performDelete = async () => {
  loading.value.delete = true;
  error.value = null;
  
  try {
    const deleted = await templateStore.deleteTemplate(templateId.value);
    
    if (deleted) {
      // 删除成功，返回模板列表
      router.push('/templates');
      // 显示成功消息
      ElMessage({
        message: '模板删除成功',
        type: 'success'
      });
    }
  } catch (err) {
    console.error('Failed to delete template:', err);
    error.value = '删除模板失败';
    // 显示错误消息
    ElMessage({
      message: '删除模板失败',
      type: 'error'
    });
  } finally {
    loading.value.delete = false;
  }
};

// 返回模板列表
const goBack = () => {
  ElMessage({
    message: '返回模板列表',
    type: 'info',
    duration: 1500
  });
  router.push('/templates');
};

// 初始加载
fetchTemplate();

// 组件卸载前清理
onBeforeUnmount(() => {
  // 销毁编辑器
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<template>
  <div class="template-detail-container">
    <!-- 加载状态 -->
    <div v-if="loading.template && !template" class="loading-state">
      <p>加载模板中...</p>
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="error-state">
      <p>{{ error }}</p>
      <button @click="goBack" class="btn-secondary">返回模板列表</button>
    </div>
    
    <!-- 模板不存在 -->
    <div v-else-if="!template" class="not-found-state">
      <p>模板不存在或已被删除</p>
      <button @click="goBack" class="btn-secondary">返回模板列表</button>
    </div>
    
    <!-- 模板详情 -->
    <div v-else>
      <div class="template-header">
        <button @click="goBack" class="back-btn">
          &larr; 返回模板列表
        </button>
        
        <div v-if="canEdit" class="template-actions">
          <button 
            v-if="!isEditMode" 
            @click="toggleEditMode" 
            class="btn-secondary"
          >
            编辑模板
          </button>
          <button 
            v-if="!isEditMode" 
            @click="deleteTemplate" 
            class="btn-danger"
            :disabled="loading.delete"
          >
            {{ loading.delete ? '删除中...' : '删除模板' }}
          </button>
        </div>
      </div>
      
      <!-- 编辑模式 -->
      <div v-if="isEditMode" class="template-edit-mode">
        <div class="form-group">
          <label for="edit-name">模板名称</label>
          <input 
            type="text" 
            id="edit-name" 
            v-model="editForm.name" 
            placeholder="输入模板名称"
          />
        </div>
        
        <div class="form-group">
          <label for="edit-category">分类</label>
          <input 
            type="text" 
            id="edit-category" 
            v-model="editForm.category" 
            placeholder="输入模板分类（可选）"
          />
        </div>
        
        <div class="form-group">
          <label for="edit-content">模板内容</label>
          <!-- 工具栏 -->
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="editorConfig"
            mode="default"
          />
          <!-- 编辑器 -->
          <Editor
            style="height: 400px; overflow-y: hidden;"
            v-model="editorValue"
            :defaultConfig="editorConfig"
            mode="default"
            @onCreated="editorRef = $event"
          />
        </div>
        
        <div class="template-footer">
          <button 
            @click="toggleEditMode" 
            class="btn-secondary"
          >
            取消
          </button>
          <button 
            @click="saveTemplate" 
            class="btn-primary"
            :disabled="loading.save"
          >
            {{ loading.save ? '保存中...' : '保存模板' }}
          </button>
        </div>
      </div>
      
      <!-- 查看模式 -->
      <div v-else class="template-view-mode">
        <h1 class="template-title">{{ template.name }}</h1>
        
        <div v-if="template.category" class="template-meta">
          <span class="template-category">{{ template.category }}</span>
        </div>
        
        <div class="template-content">
          <pre>{{ template.content }}</pre>
        </div>
        
        <div class="template-footer">
          <button 
            @click="createDocumentFromTemplate" 
            class="btn-primary"
            :disabled="loading.createDocument"
          >
            {{ loading.createDocument ? '创建中...' : '使用此模板创建文档' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.template-detail-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 2.5rem 1.5rem;
  background-color: #f9fafb;
  min-height: 100vh;
}

.template-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2.5rem;
  background-color: white;
  padding: 1.5rem 2rem;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.back-btn {
  padding: 0.625rem 1.25rem;
  background-color: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-size: 0.875rem;
  font-weight: 500;
  color: #4b5563;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.back-btn:hover {
  background-color: #f3f4f6;
  border-color: #9ca3af;
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  color: #111827;
}

.template-actions {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.template-title {
  font-size: 2rem;
  font-weight: 700;
  color: #111827;
  margin-bottom: 1.25rem;
  position: relative;
  padding-left: 1rem;
  line-height: 1.3;
}

.template-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0.25rem;
  bottom: 0.25rem;
  width: 4px;
  background-color: #4f46e5;
  border-radius: 2px;
}

.template-meta {
  margin-bottom: 2rem;
}

.template-category {
  display: inline-block;
  padding: 0.375rem 1rem;
  background-color: #f3f4f6;
  border-radius: 20px;
  font-size: 0.875rem;
  font-weight: 500;
  color: #4b5563;
  transition: all 0.3s ease;
}

.template-category:hover {
  background-color: rgba(79, 70, 229, 0.1);
  color: #4f46e5;
  transform: translateY(-2px);
}

.template-content {
  background-color: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 2rem;
  margin-bottom: 2.5rem;
  min-height: 300px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.template-content:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  border-color: rgba(79, 70, 229, 0.2);
}

.template-content pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: inherit;
  font-size: 1rem;
  line-height: 1.6;
  color: #111827;
}

.template-footer {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  background-color: white;
  padding: 1.5rem 2rem;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

/* 编辑模式样式 */
.template-edit-mode {
  display: flex;
  flex-direction: column;
  gap: 2rem;
  background-color: white;
  padding: 2rem;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 2rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.form-group label {
  font-size: 0.875rem;
  font-weight: 600;
  color: #374151;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.form-group label::before {
  content: '';
  width: 4px;
  height: 4px;
  background-color: #4f46e5;
  border-radius: 50%;
}

.form-group input {
  padding: 0.875rem 1rem;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-size: 1rem;
  width: 100%;
  background-color: #f9fafb;
  transition: all 0.3s ease;
}

.form-group input:focus {
  outline: none;
  border-color: #4f46e5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.15);
  background-color: white;
}

/* 按钮样式 */
.btn-primary,
.btn-secondary,
.btn-danger {
  padding: 0.75rem 1.75rem;
  border-radius: 8px;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  z-index: 1;
}

.btn-primary::before,
.btn-secondary::before,
.btn-danger::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.1);
  transform: scaleX(0);
  transform-origin: right;
  transition: transform 0.3s ease;
  z-index: -1;
}

.btn-primary {
  background-color: #4f46e5;
  color: white;
  border: 1px solid #4f46e5;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
}

.btn-primary:hover {
  background-color: #4338ca;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(79, 70, 229, 0.3);
}

.btn-primary:hover::before,
.btn-secondary:hover::before,
.btn-danger:hover::before {
  transform: scaleX(1);
  transform-origin: left;
}

.btn-primary:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  box-shadow: none;
  transform: none !important;
}

.btn-secondary {
  background-color: white;
  color: #4b5563;
  border: 1px solid #e5e7eb;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.btn-secondary:hover {
  background-color: #f3f4f6;
  color: #111827;
  border-color: #9ca3af;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
}

.btn-danger {
  background-color: white;
  color: #ef4444;
  border: 1px solid #ef4444;
  box-shadow: 0 2px 5px rgba(239, 68, 68, 0.1);
}

.btn-danger:hover {
  background-color: #fee2e2;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(239, 68, 68, 0.2);
}

/* 状态样式 */
.loading-state,
.error-state,
.not-found-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 1.5rem;
  padding: 4rem 2rem;
  text-align: center;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin: 2rem 0;
}

.loading-state p,
.error-state p,
.not-found-state p {
  font-size: 1.25rem;
  color: #4b5563;
  margin-bottom: 1.5rem;
  font-weight: 500;
}
</style>